﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace LostHobbits.Render
{
    class Sprite
    {
        public Texture2D texture;

        protected List<Rectangle> frames = new List<Rectangle>();
        private int frameWidth = 0;
        private int frameHeight = 0;
        private int currentFrame;
        private float frameTime = 0.1f;
        private float timeForCurrentFrame = 0.0f;

        public Sprite(            
            Texture2D texture,
            Rectangle initialFrame
            )
        {          
            this.texture = texture;            

            frames.Add(initialFrame);
            frameWidth = initialFrame.Width;
            frameHeight = initialFrame.Height;
        }

        public int Frame { get { return currentFrame; } set { currentFrame = (int)MathHelper.Clamp(value, 0, frames.Count - 1); } }
        public float FrameTime { get { return frameTime; } set { frameTime = MathHelper.Max(0, value); } }
        public Rectangle Source { get { return frames[currentFrame]; } }
        public Rectangle Destination(Vector2 location) 
        { 
            return new Rectangle((int)location.X, (int)location.Y, frameWidth, frameHeight); 
        }
        public Vector2 FrameCenter { get { return new Vector2(frameWidth / 2, frameHeight / 2); } }
        
        public void AddFrame(Rectangle frameRectangle)
        {
            frames.Add(frameRectangle);
        }

        public void Update(GameTime gameTime)
        {
            float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;

            timeForCurrentFrame = elapsed;

            if (timeForCurrentFrame >= FrameTime)
            {
                currentFrame = (currentFrame + 1) % (frames.Count);
                timeForCurrentFrame = 0.0f;
            }
        }

        public void Draw(SpriteBatch spriteBatch, Color tint, float rotation, Vector2 location)
        {
            spriteBatch.Draw(
                texture,
                location + FrameCenter,
                Source,
                tint,
                rotation,
                new Vector2(frameWidth / 2, frameHeight / 2),
                0.4f,
                SpriteEffects.None,
                0.0f);
        }
    }
}
